from django.shortcuts import render

# Create your views here.
from rest_framework.generics import ListAPIView, GenericAPIView, UpdateAPIView, ListCreateAPIView, DestroyAPIView
from rest_framework.response import Response
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.models import Area
from areas.serializers import AreaViewSerializer, AddressSerializer
from users.models import Address


class AreaView(CacheResponseMixin, ListAPIView):
    queryset = Area.objects.filter(parent=None)
    serializer_class = AreaViewSerializer


class AreasView(CacheResponseMixin, ListAPIView):
    # queryset = Area.objects.filter(parent_id=pk) 这边是获取不到ｐｋ值的，需要重写get_queryset方法
    serializer_class = AreaViewSerializer

    def get_queryset(self):
        return Area.objects.filter(parent_id=self.kwargs["pk"])


class AddressView(ListCreateAPIView, UpdateAPIView, DestroyAPIView):
    serializer_class = AddressSerializer

    # 前端需要接收默认地址ｉｄ，所以重写ｇｅｔ方法，返回对应参数
    def get(self, request, *args, **kwargs):
        addresses = self.get_queryset()
        default_address_id = request.user.default_address_id
        ser = self.get_serializer(addresses, many=True)

        return Response({"addresses": ser.data, "default_address_id": default_address_id})

    # 　自定义返回对应用户所有地址，重写get_queryset
    def get_queryset(self):
        user = self.request.user
        address = Address.objects.filter(user=user, is_deleted=False)
        return address

    # 重写delete方法实现逻辑删除
    def delete(self, request, *args, **kwargs):
        address = self.get_object()
        address.is_deleted = True
        address.save()
        return Response({"message": "ok"})


# updateapiview的逻辑与我们想要的功能不符合，所以不用
class StatusView(GenericAPIView):
    def put(self, request, pk):
        user = request.user
        user.default_address_id = pk
        user.save()
        address = Address.objects.get(id=pk)
        ser = AddressSerializer(address)
        return Response(ser.data)
